<template>
  <div class="manager-dashboard">
    <h2>管理员界面</h2>

    <div v-if="!isAdminActivated" class="activate-admin-section">
      <h3>激活管理员身份</h3>
      <div class="form-group">
        <label for="adminPassword">请输入管理员密码:</label>
        <input type="password" id="adminPassword" v-model="adminPassword" @keyup.enter="activateAdmin" />
        <button @click="activateAdmin">激活</button>
      </div>
      <p v-if="activationMessage" :class="{'success': isActivationSuccess, 'error': !isActivationSuccess}">
        {{ activationMessage }}
      </p>
    </div>

    <div v-if="isAdminActivated">
      <h1>积分商城商品管理</h1>
      
      <div v-if="message" class="message" @click="message = ''">
        {{ message }}
      </div>
      
      <div class="action-buttons">
        <button @click="showForm = true; resetForm()" class="add-button">
          添加新商品
        </button>
      </div>
      
      <div v-if="showForm" class="form-modal">
        <div class="form-content">
          <h2>{{ isEditMode ? '编辑商品' : '添加新商品' }}</h2>
          
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label>商品图片</label>
              <div class="image-upload-container">
                <label class="image-upload-label">
                  <input type="file" accept="image/*" @change="handleImageChange" hidden>
                  <span v-if="!previewImage">选择图片</span>
                  <img v-if="previewImage" :src="previewImage" alt="商品预览">
                </label>
              </div>
            </div>
            
            <div class="form-group">
              <label>商品名称*</label>
              <input v-model="formData.title" placeholder="输入商品名称">
              <span class="error" v-if="errors.title">{{ errors.title }}</span>
            </div>
            
            <div class="form-group">
              <label>商品类型*</label>
              <select v-model="formData.type">
                <option :value="ITEM_TYPE.PHYSICAL">实体商品</option>
                <option :value="ITEM_TYPE.FRAME">用户头像框</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>商品描述</label>
              <textarea v-model="formData.description" placeholder="输入商品描述"></textarea>
            </div>
            
            <div class="form-group">
              <label>价格(积分)*</label>
              <input type="number" v-model.number="formData.price" min="0">
              <span class="error" v-if="errors.price">{{ errors.price }}</span>
            </div>
            
            <div class="form-group">
              <label>库存数量*</label>
              <input type="number" v-model.number="formData.inventory" min="0">
              <span class="error" v-if="errors.inventory">{{ errors.inventory }}</span>
            </div>
            
            <div class="form-actions">
              <button type="button" @click="showForm = false" class="cancel-button" :disabled="isUploading">
                取消
              </button>
              <button type="submit" class="submit-button" :disabled="isUploading">
                {{ isUploading ? '处理中...' : (isEditMode ? '更新商品' : '添加商品') }}
              </button>
            </div>
          </form>
        </div>
      </div>
      
      <div class="item-list">
        <table>
          <thead>
            <tr>
              <th>图片</th>
              <th>名称</th>
              <th>类型</th>
              <th>价格</th>
              <th>库存</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in items" :key="item.id">
              <td>
                <img v-if="item.image" :src="imagePath.getServerImagePath(item.image)" class="item-thumbnail">
                <span v-else>无图片</span>
              </td>
              <td>{{ item.title }}</td>
              <td>{{ getTypeName(item.type) }}</td>
              <td>{{ item.price }}积分</td>
              <td>{{ item.inventory }}</td>
              <td>
                <button @click="editItem(item)" class="edit-button">编辑</button>
                <button 
                   @click="deleteItem(item.id)" 
       class="delete-button"
      :disabled="item.type === ITEM_TYPE.VIRTUAL"
      :title="item.type === ITEM_TYPE.VIRTUAL ? '虚拟卡类型不可删除' : ''"
    >
      删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { shopItemService } from '@/services/shop_item'
import { imagePath } from '@/utils/image' 
import { userManager } from '@/utils/user';
import { tokenManager } from '@/utils/token';

const ADMIN_MASTER_PASSWORD = "123456"; 

const adminPassword = ref('');
const isAdminActivated = ref(false); 
const activationMessage = ref('');
const isActivationSuccess = ref(false);

const ITEM_TYPE = {
  VIRTUAL: 0, 
  PHYSICAL: 1,
  FRAME: 2 // 用户头像框
}

const formData = ref({
  imageFile: null,
  title: '',
  type: ITEM_TYPE.VIRTUAL,
  description: '',
  price: 0,
  inventory: 0  
})

const previewImage = ref('')
const items = ref([])
const errors = ref({})
const message = ref('')
const showForm = ref(false)
const isEditMode = ref(false)
const currentItemId = ref(null)
const isUploading = ref(false)

const getTypeName = (type) => {
  switch(type) {
    case ITEM_TYPE.VIRTUAL: return '积分卡';
    case ITEM_TYPE.PHYSICAL: return '实体商品';
    case ITEM_TYPE.FRAME: return '头像框';
    default: return '未知类型';
  }
}

const activateAdmin = () => {
  if (!adminPassword.value) {
    activationMessage.value = '密码不能为空。';
    isActivationSuccess.value = false;
    return;
  }
  if (adminPassword.value === ADMIN_MASTER_PASSWORD) {
    isAdminActivated.value = true;
    activationMessage.value = '管理员身份激活成功！';
    isActivationSuccess.value = true;
    fetchItems();
  } else {
    isAdminActivated.value = false;
    activationMessage.value = '管理员密码不正确。';
    isActivationSuccess.value = false;
  }
  adminPassword.value = ''; 
};

const fetchItems = async () => {
  try {
    shopItemService.getShopItems((res)=>{
      items.value = res.data
    })
  } catch (error) {
    console.error('获取商品列表失败:', error)
    message.value = '获取商品列表失败'
  }
}

const handleImageChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    formData.value.imageFile = file
    previewImage.value = URL.createObjectURL(file)
  }
}

const submitForm = async () => {
  if (!validateForm()) return
  
  isUploading.value = true
  
  try {
    const formDataObj = new FormData()
    
    if (formData.value.imageFile) {
      formDataObj.append('image', formData.value.imageFile)
    }
    
    formDataObj.append('title', formData.value.title)
    formDataObj.append('type', formData.value.type)
    formDataObj.append('description', formData.value.description)
    formDataObj.append('price', formData.value.price)
    formDataObj.append('inventory', formData.value.inventory) 
    
    if (isEditMode.value) {
      await shopItemService.updateShopItem(currentItemId.value, formDataObj)
      message.value = '商品更新成功'
    } else {
      await shopItemService.addShopItem(formDataObj,(res)=>{
        console.log(res)
      })
      message.value = '商品添加成功'
    }
    
    resetForm()
    fetchItems()
    showForm.value = false
  } catch (error) {
    console.error('操作失败:', error)
    message.value = error.response?.data?.message || '操作失败'
  } finally {
    isUploading.value = false
  }
}

const validateForm = () => {
  errors.value = {}
  let isValid = true
  
  if (!formData.value.title) {
    errors.value.title = '请输入商品名称'
    isValid = false
  }
  
  if (formData.value.price <= 0) {
    errors.value.price = '价格必须大于0'
    isValid = false
  }
  
  if (formData.value.inventory === null || formData.value.inventory === undefined) {
    errors.value.inventory = '请输入库存数量'
    isValid = false
  } else if (formData.value.inventory < 0) {
    errors.value.inventory = '库存不能为负数'
    isValid = false
  }
  
  return isValid
}

const resetForm = () => {
  formData.value = {
    imageFile: null,
    title: '',
    type: ITEM_TYPE.VIRTUAL,
    description: '',
    price: 0,
    inventory: 0
  }
  previewImage.value = ''
  currentItemId.value = null
  errors.value = {}
  isEditMode.value = false
}

const editItem = (item) => {
  formData.value = {
    imageFile: null,
    title: item.title,
    type: item.type,
    description: item.description,
    price: item.price,
    inventory: item.inventory || 0
  }
  previewImage.value = item.image || ''
  currentItemId.value = item.id
  isEditMode.value = true
  showForm.value = true
}

const deleteItem = async (id) => {
    const itemToDelete = items.value.find(item => item.id === id);
  
  // 检查是否是虚拟卡类型
  if (itemToDelete && itemToDelete.type === ITEM_TYPE.VIRTUAL) {
    message.value = '虚拟卡类型不可删除';
    return;
  }
  if (!confirm('确定要删除这个商品吗？')) return
  try {
    await shopItemService.deleteShopItem(id)
    message.value = '商品删除成功'
    fetchItems()
  } catch (error) {
    console.error('删除失败:', error)
    message.value = error.response?.data?.message || '删除失败'
  }
}

onMounted(() => {
  // 页面加载时，不直接加载商品列表，而是等待激活
})
</script>

<style scoped>
/* 此处修改：调整 .activate-admin-section 的内部布局和 input 宽度 */
.activate-admin-section {
  background-color: #ffffff;
  
  padding: 40px;
  border-radius: 12px;
  margin: 50px auto;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  text-align: center;
  max-width: 500px;
  border: none;
}

.activate-admin-section h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
  font-weight: 600;
}

.activate-admin-section .form-group {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.activate-admin-section label {
  font-weight: 500;
  color: #555;
  flex-shrink: 0;
  text-align: right;
  margin-right: 5px;
}

.activate-admin-section input {
  padding: 12px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 16px;
  width: 200px;
  max-width: 50%;
  flex-grow: 1;
  flex-shrink: 1;
  box-sizing: border-box;
  transition: border-color 0.3s, box-shadow 0.3s;
}

.activate-admin-section input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  outline: none;
}

.activate-admin-section button {
  padding: 12px 25px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.3s ease, transform 0.2s ease;
  flex-shrink: 0;
}

.activate-admin-section button:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
}

.activation-message {
  margin-top: 25px;
  font-size: 14px;
  padding: 10px 15px;
  border-radius: 8px;
}

.activation-message.success {
  color: #67c23a;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}

.activation-message.error {
  color: #f56c6c;
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}

.manager-dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  color: #333;
  margin-bottom: 20px;
  text-align: center; 
}

.message {
  padding: 10px 15px;
  background-color: #4CAF50;
  color: white;
  margin-bottom: 20px;
  border-radius: 4px;
  cursor: pointer;
}

.action-buttons {
  margin-bottom: 20px;
  text-align: right; 
}

.add-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-button:hover {
  background-color: #0b7dda;
}

.form-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.form-content h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group textarea {
  height: 100px;
  resize: vertical;
}

.error {
  color: #f44336;
  font-size: 14px;
  display: block;
  margin-top: 5px;
}

.image-upload-container {
  margin-top: 10px;
}

.image-upload-label {
  display: inline-block;
  cursor: pointer;
  border: 1px dashed #ddd;
  padding: 20px;
  text-align: center;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.image-upload-label img {
  max-width: 100%;
  max-height: 200px;
  display: block;
  margin: 0 auto;
}

.upload-progress {
  margin-top: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  height: 20px;
  position: relative;
}

.progress-bar {
  background-color: #4CAF50;
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.upload-progress span {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #333;
  font-size: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

.cancel-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.item-list {
  margin-top: 30px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.item-thumbnail {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.edit-button {
  background-color: #FFC107;
  color: #333;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 5px;
}

.delete-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

@media (max-width: 768px) {
  table {
    display: block;
    overflow-x: auto;
  }
  
  .form-content {
    padding: 20px;
  }
}
</style>